﻿using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MachineStatusClient
{
    public partial class TimerUserControl : UserControl
    {
        BContentToSqlServer bts = new BContentToSqlServer();

        public TimerUserControl()
        {
            InitializeComponent();

            //// 设置日期时间选择器格式
            //dateTimePickerStart.Format = DateTimePickerFormat.Custom;
            //dateTimePickerStart.CustomFormat = "yyyy-MM-dd";
            //dateTimePickerStart.ShowUpDown = true;  // 启用时间选择模式

            //dateTimePickerEnd.Format = DateTimePickerFormat.Custom;
            //dateTimePickerEnd.CustomFormat = "yyyy-MM-dd";
            //dateTimePickerEnd.ShowUpDown = true;

            // 添加Enter事件处理程序
            //dateTimePickerStart.Enter += Control_Enter;
            //dateTimePickerEnd.Enter += Control_Enter;
        }

        private void TimerUserControl_Load(object sender, EventArgs e)
        {
            dateTimePickerStart.Value = DateTime.Now.AddDays(-1);
            dateTimePickerEnd.Value = DateTime.Now;
            BindWorkOrdersToDataGridView(new TimerSearchModel
            {
                StartTime = dateTimePickerStart.Value,
                EndTime = dateTimePickerEnd.Value,
            });
        }


        private void BindWorkOrdersToDataGridView(TimerSearchModel searchCondition = null)
        {
            try
            {
                // 1. 从配置读取设备编码
                //string machineId = ConfigurationManager.AppSettings["DeviceCode"];
                dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                dataGridView1.ColumnHeadersHeight = 50;
                //if (string.IsNullOrEmpty(machineId))
                //{
                //    MessageBox.Show("设备编码未配置！");
                //    return;
                //}
                var condition = searchCondition ?? new TimerSearchModel();
                // 2. 调用接口获取数据
                List<TimerModel> workOrders = bts.GetTimer(condition);

                // 3. 绑定到DataGridView
                if (workOrders != null && workOrders.Count > 0)
                {
                    // 配置列映射（字段名 -> 列名）
                    //dataGridView1.AutoGenerateColumns = false; // 禁止自动生成列
                    // 设置开始时间和结束时间列的格式
                    if (dataGridView1.Columns.Contains("Column2"))
                    {
                        dataGridView1.Columns["Column2"].DefaultCellStyle.Format = "yyyy-MM-dd";
                        dataGridView1.Columns["Column2"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    }
                    //if (dataGridView1.Columns.Contains("Column6"))
                    //{
                    //    dataGridView1.Columns["Column6"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    //    dataGridView1.Columns["Column6"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    //}
                    // 绑定数据源
                    dataGridView1.DataSource = workOrders;

                    dataGridView1.RowTemplate.Height = 50;
                    //Message.Text = "";
                }
                else
                {
                    //MessageBox.Show("未查询到工单数据");
                    //Message.Text = "未查询到工单排程数据";
                    //Message.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"加载数据失败: {ex.Message}");
                //Message.Text = $"加载数据失败: {ex.Message}";
                //Message.ForeColor = Color.Red;
            }
        }

        private void buttonTimerSearch_Click(object sender, EventArgs e)
        {
            TimerSearchModel searchModel = new TimerSearchModel
            {
                StartTime = dateTimePickerStart.Value,
                EndTime = dateTimePickerEnd.Value
            };
            BindWorkOrdersToDataGridView(searchModel);
        }

        // 添加Windows API导入
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        // 其他现有代码...

        // 添加显示屏幕键盘的方法
        private void ShowOnScreenKeyboard()
        {
            try
            {
                // 检查屏幕键盘是否已经在运行
                var oskProcess = Process.GetProcessesByName("osk").FirstOrDefault();

                if (oskProcess == null)
                {
                    // 启动屏幕键盘
                    Process.Start("osk.exe");
                }
                else
                {
                    // 如果已经在运行，将其带到前台
                    SetForegroundWindow(oskProcess.MainWindowHandle);
                }
            }
            catch (Exception ex)
            {
                // 如果无法启动屏幕键盘，可以尝试其他方法
                try
                {
                    // 尝试使用tabtip (Windows 10触摸键盘)
                    Process.Start("tabtip.exe");
                }
                catch
                {
                    MessageBox.Show("无法启动屏幕键盘: " + ex.Message);
                }
            }
        }

        // 添加Enter事件处理程序
        private void Control_Enter(object sender, EventArgs e)
        {
            ShowOnScreenKeyboard();
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void dateTimePickerEnd_ValueChanged(object sender, EventArgs e)
        {

        }

        private void dateTimePickerStart_ValueChanged(object sender, EventArgs e)
        {

        }
    }
}
